<template>
  <z-modal
      v-bind="modalOption"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="validatorRules">
        <a-form-model-item label="群组名称" prop="groupName">
          <a-input placeholder="请输入群组名称" :disabled="disableSubmit" v-model.trim="form.groupName"/>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </z-modal>
</template>

<script>
import ModalFormMixin from '@/mixins/ModalFormMixin'
import { postAction, putAction } from '@/services/manage'

export default {
  name: 'GroupModal',
  mixins: [ModalFormMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: {},
      validatorRules: {
        groupName: [{ required: true, message: '请输入群组名称!' }]
      },
      disableSubmit: false,
      url: {
        add: '/doc/group/v1/add',
        edit: '/doc/group/v1/edit'
      }
    }
  },
  methods: {
    // 确定
    handleOk() {
      // 触发表单验证
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const formData = Object.assign(this.model, this.form)
          if (formData.id) {
            putAction(this.url.edit, formData).then(res => {
              this.resSuccess(res)
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            postAction(this.url.add, formData).then(res => {
              this.resSuccess(res)
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        }
      })
    },
    resSuccess(res) {
      if (res.success) {
        this.$message.success('操作成功')
        this.$emit('ok')
        this.close()
      } else {
        this.$message.warning(res.message)
      }
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.$refs.ruleForm.resetFields()
      this.visible = false
    }
  }
}
</script>
